package jamdodge;

import jamdodge.app.MainScreen;

import java.util.Random;
import java.util.zip.CRC32;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.Log;

public class UserID {
	private String _userID;
	
	public String GetUserID() 
	{
		return _userID;
	}

	public UserID(Activity activity)
	{
		String id = LoadUserID(activity, MainScreen.APP_NAME);
    	
    	//this should only ever be called on first run of program:
    	if (id == "")
    	{
    		TelephonyManager tmanager = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
        	String imei = tmanager.getDeviceId();
    		
        	Log.i(MainScreen.APP_NAME, "DeviceId is null. Possibly running in emulator.");
        	
    		id = CreateUserID(imei);
    		SaveUserID(activity, MainScreen.APP_NAME, id);
    		
    		Log.i(MainScreen.APP_NAME, "UserID created: " + id);
    	}
    	
    	if (id == "")
    	{
    		Log.e(MainScreen.APP_NAME, "UserID is null. Could not create or load.");
    	}
    	
    	_userID = id;
	}
	
	/**
	 * Creates a unique user ID for this device by using a unique number such as the IMEI, a salt and a CRC32 hash.
	 * @param unique A unique string to identify this device.
	 * @return A unique user ID.
	 */
	public String CreateUserID(String unique)
	{
		Random rnd = new Random();
		
		int saltPos = rnd.nextInt(unique.length());
		int saltValue = rnd.nextInt(10); //[0,10) = [0,9]
		
		//shift the unique string up one character and add in the
		//salt in the open place
		byte[] chars = new byte[unique.length() + 1];
		for (int i = 0; i < unique.length() + 1; i++)
		{
			if (i != saltPos)
			{
				chars[i] = (byte) Integer.toString(saltValue).charAt(0);
			}
			else
			{
				chars[i] = (byte)unique.charAt(i);
			}
		}
		
		CRC32 crc = new CRC32();
		crc.update(chars);
		
		return Long.toString(crc.getValue());
	}
	
	
	
	/**
	 * Gets the user ID for this device that is stored. If no ID is stored then an empty string is returned.
	 * @param activity The activity that requires the user ID.
	 * @param prefsName The name of the shared preferences file to use.
	 * @return The stored user ID or an empty string if it doesn't exist.
	 */
	private String LoadUserID(Activity activity, String prefsName)
	{
		SharedPreferences prefs = activity.getSharedPreferences(prefsName, 0);
		
		if (prefs == null)
			return "";
		
		String userid = prefs.getString("USERID", "");
		
		return userid;
	}
	
	private boolean SaveUserID(Activity activity, String prefsName, String userID)
	{
		SharedPreferences prefs = activity.getSharedPreferences(prefsName, 0);
		
		if (prefs == null)
			return false;
		
		SharedPreferences.Editor editor = prefs.edit();
		
		editor.putString("USERID", userID);
		editor.commit();
		
		return true;
	}
}
